<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElCard, ElRow, ElCol, ElButton, ElPagination, ElMessage } from 'element-plus'
import { useCartStore } from '@/stores/cart'
import CommonHeader from '@/components/CommonHeader.vue'
import CommonFooter from '@/components/CommonFooter.vue'
import FloatingSidebar from '@/components/FloatingSidebar.vue'
import { getParentCategoryService, getChildCategoryService } from '@/api/product.js'

const route = useRoute()
const router = useRouter()
const categoryType = ref(route.params.type)

// 分类数据
const categories = ref([])
// 获取分类列表
const getParentCategory = async() => {
  let result = await getParentCategoryService()
  if (result.code === 200) { 
    categories.value = result.data;
  }
}

const currentCategory = ref({
  name: '',
  products: []
})

// 获取当前分类商品列表
const getCategoryList = async (categoryId) => {
  console.log('开始获取分类商品列表, categoryId:', categoryId)
  try {
    let result = await getChildCategoryService(categoryId)
    console.log('获取商品列表结果:', result)
    
    if (result.code === 200) {
      console.log('获取商品列表成功，数据:', result.data)
      currentCategory.value.products = result.data || []
    } else {
      console.log('获取商品列表失败，错误码:', result.code)
      ElMessage.error('获取商品列表失败')
      currentCategory.value.products = []
    }
  } catch (error) {
    console.error('获取商品列表出错:', error)
    ElMessage.error('获取商品列表失败')
    currentCategory.value.products = []
  }
}

// 监听路由变化
watch(() => route.params.type, async (newType) => {
  console.log('路由参数变化:', newType)
  console.log('当前分类列表:', categories.value)
  
  // 根据url匹配分类
  const matchedCategory = categories.value.find(category => category.url === newType)
  console.log('匹配到的分类:', matchedCategory)
  
  if (matchedCategory) {
    currentCategory.value.name = matchedCategory.name
    await getCategoryList(matchedCategory.id)
  } else {
    console.log('未找到匹配的分类')
  }
}, { immediate: true })

onMounted(async () => {
  console.log('组件挂载, 当前路由参数:', route.params.type)
  // 获取分类列表
  await getParentCategory()
  console.log('获取到的分类列表:', categories.value)
  
  const matchedCategory = categories.value.find(category => category.url === route.params.type)
  console.log('初始化匹配到的分类:', matchedCategory)
  
  if (matchedCategory) {
    currentCategory.value.name = matchedCategory.name
    await getCategoryList(matchedCategory.id)
  } else {
    console.log('初始化未找到匹配的分类')
  }
})

// 模拟商品数据
const mockProducts = [
  {
    id: 1,
    name: '2024新款春季连衣裙',
    price: 199.00,
    image: 'https://img.alicdn.com/imgextra/i1/2200724907121/O1CN01Z5paLz22AdGf4cJzq_!!2200724907121.jpg',
    storeName: '时尚女装旗舰店',
    sales: 2345
  },
  {
    id: 2,
    name: '男士休闲运动套装',
    price: 299.00,
    image: 'https://img.alicdn.com/imgextra/i2/2200724907121/O1CN01Z5paLz22AdGf4cJzq_!!2200724907121.jpg',
    storeName: '运动户外专营店',
    sales: 1890
  },
  {
    id: 3,
    name: '儿童益智玩具套装',
    price: 99.00,
    image: 'https://img.alicdn.com/imgextra/i3/2200724907121/O1CN01Z5paLz22AdGf4cJzq_!!2200724907121.jpg',
    storeName: '玩具天地',
    sales: 3456
  },
  {
    id: 4,
    name: '智能手表',
    price: 599.00,
    image: 'https://img.alicdn.com/imgextra/i4/2200724907121/O1CN01Z5paLz22AdGf4cJzq_!!2200724907121.jpg',
    storeName: '数码电子旗舰店',
    sales: 1234
  },
  {
    id: 5,
    name: '厨房多功能料理机',
    price: 399.00,
    image: 'https://img.alicdn.com/imgextra/i1/2200724907121/O1CN01Z5paLz22AdGf4cJzq_!!2200724907121.jpg',
    storeName: '家电专营店',
    sales: 890
  },
  {
    id: 6,
    name: '女士真皮手提包',
    price: 299.00,
    image: 'https://img.alicdn.com/imgextra/i2/2200724907121/O1CN01Z5paLz22AdGf4cJzq_!!2200724907121.jpg',
    storeName: '箱包旗舰店',
    sales: 1567
  },
  {
    id: 7,
    name: '男士商务皮鞋',
    price: 459.00,
    image: 'https://img.alicdn.com/imgextra/i3/2200724907121/O1CN01Z5paLz22AdGf4cJzq_!!2200724907121.jpg',
    storeName: '鞋类专营店',
    sales: 2345
  },
  {
    id: 8,
    name: '家用智能扫地机器人',
    price: 1299.00,
    image: 'https://img.alicdn.com/imgextra/i4/2200724907121/O1CN01Z5paLz22AdGf4cJzq_!!2200724907121.jpg',
    storeName: '智能家居旗舰店',
    sales: 3456
  }
]

// 当前页码
const currentPage = ref(1)
// 每页显示的记录数
const pageSize = ref(12)
// 计算当前页的商品
const paginatedProducts = computed(() => {
  console.log('计算分页数据:', {
    currentCategory: currentCategory.value,
    products: currentCategory.value?.products,
    currentPage: currentPage.value,
    pageSize: pageSize.value
  })
  
  if (!currentCategory.value?.products) {
    console.log('products为空，返回空数组')
    return []
  }
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  const result = currentCategory.value.products.slice(start, end)
  console.log('分页结果:', result)
  return result
})

// 导航到商品详情
const navigateToProduct = (productId) => {
  router.push(`/home/product/${productId}`)
}

// 加入购物车
const cartStore = useCartStore()
const handleAddToCart = (product) => {
  cartStore.addToCart(product)
  ElMessage.success('商品已加入购物车！')
}
</script>

<template>
  <CommonHeader />
  <FloatingSidebar />
  <div class="category-page">
    <div class="container">
      <h1 class="page-title">{{ currentCategory.name }}</h1>

      <!-- 商品列表 -->
      <div class="product-list">
        <el-row :gutter="20">
          <el-col :span="6" v-for="product in paginatedProducts" :key="product.id">
            <el-card class="product-card" shadow="hover">
              <img :src="product.image" class="product-image" @click="navigateToProduct(product.id)" />
              <div class="product-info">
                <h3 class="product-name-card" @click="navigateToProduct(product.id)">
                  {{ product.name }}
                </h3>
                <div class="store-sales">
                  <span class="store-name">{{ product.storeName }}</span>
                  <span class="sales">销量: {{ product.sales }}</span>
                </div>
                <div class="price">¥{{ product.price }}</div>
                <el-button type="primary" @click="handleAddToCart(product)">
                  加入购物车
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="currentCategory.products.length"
          layout="prev, pager, next"
        />
      </div>
    </div>
  </div>
    <!-- 页脚 -->
    <CommonFooter />
</template>

<style scoped>
.category-page {
  padding: 20px;
  min-height: calc(100vh - 120px);
}

.container {
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
}

.product-list {
  margin-bottom: 40px;
}

.product-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.product-info {
  padding: 14px;
}

.product-info h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin: 10px 0;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.product-name-card {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.store-sales {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  margin-bottom: 8px;
}

.store-name {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.sales {
  margin-left: 10px;
}

.product-info .el-button {
  width: 100%;
}
</style> 